//
//  LoveExperienceViewController.m
//  Molian
//
//  Created by 小蚕科技 on 15/6/1.
//  Copyright (c) 2015年 xiaocan. All rights reserved.
//

#import "LoveExperienceViewController.h"
#import "RelationQQWXTableViewCell.h"
#import "MLUserDataViewController.h"
#import "PhotoAttestationViewController.h"
#import "TestViewController.h"
#import "BindingMobilePhoneViewController.h"
#import "PhoneViewController.h"
#import "WEBViewController.h"
@interface LoveExperienceViewController ()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate,PhotoAttestationViewControllerDelegate,BindingMobilePhoneViewControllerDelegate>
{
    
    
}

@property BOOL userData;//用户资料是否完整
@property BOOL userAttestationImage;//是否上传认证照片
@property (nonatomic, strong)UITableView *tableView;
@property (nonatomic, strong)NSArray *titleArr;
//@property (nonatomic, strong)UISwitch *mySwitch;//我要上编辑推荐开关
//@property (nonatomic, strong)UITextField *qqOrWX;
@property (nonatomic, strong)MLAuthentication *loveExperience;
@property (nonatomic, strong)UIImage *selectImage;//照片认证中的头像
@property BOOL isSubmit;//是否提交过了
@property BOOL isTest;//已通过测试题；
//@property BOOL isPhone;//是否绑定手机号
@property BOOL isRead;//是否已经阅读申请须知
@end

@implementation LoveExperienceViewController
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self dataFull];
    [self.tableView reloadData];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
   // self.isPhone = NO;
    self.isRead = NO;
    self.isTest = NO;
    /*
     TestViewController 测试题
     
     */
    self.title = @"申请";
    self.isSubmit = NO;
    self.titleArr = @[@[@"mine_more_apply-for-lover_banner_img"],@[@"照片认证",@"个人资料"],@[@"测试题"],@[@"申请须知"]];
    
    self.userData = NO;
    self.userAttestationImage = NO;
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, DeviceWidth, DeviceHeight)style:UITableViewStylePlain];
    self.tableView.backgroundColor = APPCOLORBACKGROUNDCOLOR(1);
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.scrollsToTop = YES;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    self.tableView.tableFooterView = [[UIView alloc] init];//不显示空的cell
    [self.view addSubview:self.tableView];
    
    UIBarButtonItem *rightItem  = [[UIBarButtonItem alloc]initWithTitle:@"提交" style:UIBarButtonItemStylePlain target:self action:@selector(saveUserInfo)];
    self.navigationItem.rightBarButtonItem = rightItem;
    
    UIBarButtonItem *leftItem  = [[UIBarButtonItem alloc]initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(clickLeft)];
    self.navigationItem.leftBarButtonItem = leftItem;
    self.loveExperience =[MLAuthentication object];
    _loveExperience.sponsor = [MLUser currentUser];
    _loveExperience.status = AuthenticationStatus_APPLYING;
    _loveExperience.needRecommend = MLAuthenticationNeedRecommend_NO;
    
    //检查是否提交过
    [self inspectSubmit];
    // Do any additional setup after loading the view.
}
- (void)clickLeft
{
    [AVAnalytics event:@"申请成为专属恋人"]; // 通知服务器一个点击事件。
    if (self.userAttestationImage) {
        HUD*hud = [[HUD alloc]init];
        [hud HUDImage:nil Title:@"提示" Content:@"如果放弃,此次的编辑内容将不会保存,确定放弃?" CANCEL:@"取消" Confirm:@"确定"];
        
        hud.Confirm = ^{
            [self.navigationController popViewControllerAnimated:YES];
            //确定
        };
        hud.Cancel = ^{
            //取消
        };
        [self.view addSubview:hud];
    }else{
        [self.navigationController popViewControllerAnimated:YES];
    }
}
//检查是否提交过(正在审核)
- (void)inspectSubmit
{
    AVQuery *q =[MLAuthentication query];
    [q whereKey:@"sponsor" equalTo:[MLUser currentUser]];
    [q whereKey:@"needRecommend" equalTo:[NSNumber numberWithInteger:MLAuthenticationNeedRecommend_NO]];
    [q whereKey:@"status" equalTo:[NSNumber numberWithInteger:AuthenticationStatus_APPLYING]];
    [q findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (!error&&objects.count) {
            self.isSubmit = YES;
            [HUD Prompt:@"已有申请资料在审核中"];
        }
    }];
}
//提交
- (void)saveUserInfo
{
    self.navigationItem.rightBarButtonItem.enabled = NO;
    
    if(self.isSubmit ==  NO){
        
        if(self.userData&&self.userAttestationImage){
            //再次检查
            if (!self.isTest) {
                [HUD Prompt:@"测试题还没有通过哦"];
                return;
            }
//            if (!self.isPhone) {
//                [HUD Prompt:@"还没有绑定短信通知号码"];
//                return;
//            }
            if (!self.isRead) {
                [HUD Prompt:@"还没有阅读申请须知"];
                return;
            }
            AVQuery *q =[MLAuthentication query];
            [q whereKey:@"sponsor" equalTo:[MLUser currentUser]];
            [q whereKey:@"status" equalTo:[NSNumber numberWithInteger:AuthenticationStatus_APPLYING]];
            [q whereKey:@"needRecommend" equalTo:[NSNumber numberWithInteger:MLAuthenticationNeedRecommend_NO]];
            [q findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
                if (!error&&objects.count) {
                    self.navigationItem.rightBarButtonItem.enabled = YES;
                    
                    self.isSubmit = YES;
                    [HUD Prompt:@"已有申请资料在审核中"];
                }else{
                    //可以提交
                    self.loveExperience.needRecommend = MLAuthenticationNeedRecommend_NO;
                    self.loveExperience.contact =  [MLUser currentUser].notifyPhoneNum;
                    [self.loveExperience saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                        
                        if (succeeded) {
                            self.navigationItem.rightBarButtonItem.enabled = YES;
                            [self.navigationController popViewControllerAnimated:YES];
                            [HUD Prompt:@"提交成功"];
                        }else{
                            self.navigationItem.rightBarButtonItem.enabled = YES;
                            [HUD Prompt:@"提交失败"];
                        }
                        
                    }];
                }
            }];
            
        }else{
            self.navigationItem.rightBarButtonItem.enabled = YES;
            [HUD Prompt:@"信息不完整不能提交哦"];
            
        }
   
    }else{
        self.navigationItem.rightBarButtonItem.enabled = YES;
        [HUD Prompt:@"已有申请资料在审核中"];
    }
    
    
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.titleArr.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    }else if (section == 1){
        return 2;
    }else if (section == 2){
        return 1;
    }else if(section == 3){
        return 1;
    }else{
        return 0;
    }
}
- (BOOL)isNSString:(NSString *)str
{
    if (str&&str.length) {
        return YES;
    }
    return NO;
}
- (BOOL)isNSDate:(NSDate *)date
{
    if (date) {
        return YES;
    }
    return NO;
}
- (BOOL)isNSArray:(NSArray *)arr
{
    if (arr&&arr.count) {
        return YES;
    }
    return NO;
}
//资料完整度
- (void)dataFull
{
    MLUser *u = [MLUser currentUser];
    __block  NSInteger a = 0;
    //个人资料
    //昵称
    [self isNSString:u.nickname]==YES?a++:a;
    [self isNSDate:u.birthday]==YES?a++:a;
    [self isNSString:u.location_city]==YES?a++:a;
    //个人签名
    [self isNSString:u.intro]==YES?a++:a;
    u.isHasVoice==YES?a++:a;
    [self isNSString:u.belong]==YES?a++:a;
    //喜欢
    [self isNSArray:u.like_tags]==YES?a++:a;
    //叫我
    [self isNSArray:u.called_tags]==YES?a++:a;
    //外貌
    [self isNSString:u.figure]==YES?a++:a;
    //职业
    [self isNSString:u.job]==YES?a++:a;
    
    //语言
    [self isNSArray:u.language]==YES?a++:a;
    
    //特技
    [self isNSArray:u.special]==YES?a++:a;
    //兴趣话题
    [self isNSString:u.interestTopic]==YES?a++:a;
    //我想
     [self isNSArray:u.want_tags]==YES?a++:a;
    //理想的你
     [self isNSArray:u.ideal_tags]==YES?a++:a;
    
    AVQuery *galleryQuery = [MLGallery query];
    [galleryQuery whereKey:@"belong_to" equalTo:u];
    [galleryQuery includeKey:@"images"];
    [galleryQuery getFirstObjectInBackgroundWithBlock:^(AVObject *object, NSError *error) {
        MLGallery *gallery = (MLGallery *)object;
        //图片集
        if ( gallery.images&& gallery.images.count) {
            a = a+gallery.images.count;
        }
        
        if (a>=23) {
            self.userData = YES;
            //已完成
            [self.tableView reloadData];
        }
    }];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"logo"];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"logo"];
            UIImageView *logoImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, DeviceWidth, DeviceWidth/320*144)];
            logoImageView.image = [UIImage imageNamed:[[self.titleArr objectAtIndex:indexPath.section] objectAtIndex:indexPath.row]];
            [cell addSubview:logoImageView];
        }
        return cell;
        
    }else if (indexPath.section == 1||indexPath.section == 2||indexPath.section == 3){
        static  NSString *CellIdentifier = @"DataCell" ;
        //自定义cell类
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if  (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
        }
        //防止产生重影,首先移除子视图
        NSArray *subviews = [[NSArray alloc]initWithArray:cell.contentView.subviews];
        for (UIView *subview in subviews) {
            [subview removeFromSuperview];
        }
        
        [cell setSeparatorInset:UIEdgeInsetsZero];
        NSString *str = [[self.titleArr objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
        CGFloat w = str.length*15+10;
        
        //cell的右边有一个小箭头，距离右边有十几像素；
        UILabel *cellTitle = [[UILabel alloc]initWithFrame:CGRectMake(20, 0, w, 50)];
        cell.selectionStyle = UITableViewCellSelectionStyleDefault;
        cell.backgroundColor = [UIColor whiteColor];
        cellTitle.textColor = RGBA(51, 51, 51, 1);
        cellTitle.font = [UIFont fontWithName:FontName size:14];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        
        cellTitle.text = str;
        [cell.contentView addSubview:cellTitle];
        
        UILabel *assistant = [[UILabel alloc]initWithFrame:CGRectMake(20+w , 17.5, 50, 15)];
        if (indexPath.section == 1) {
            if (indexPath.row == 0) {
                if (self.userAttestationImage) {
                    assistant.backgroundColor =RGBA(75, 217, 112, 1);
                    assistant.textColor = [UIColor whiteColor];
                    assistant.text = @"已上传";
                }else{
                    assistant.backgroundColor =RGBA(202, 203, 204, 1);
                    assistant.textColor = [UIColor whiteColor];
                    assistant.text = @"未上传";
                }
            }else{
                if (self.userData) {
                    assistant.backgroundColor =RGBA(75, 217, 112, 1);
                    assistant.textColor = [UIColor whiteColor];
                    assistant.text = @"已完整";
                }else{
                    assistant.backgroundColor =RGBA(202, 203, 204, 1);
                    assistant.textColor = [UIColor whiteColor];
                    assistant.text = @"未完整";
                }
            }
        }else if (indexPath.section == 2){
            NSUserDefaults *userD =[NSUserDefaults standardUserDefaults];
            MLUser *user = [MLUser currentUser];
            NSString *str = [userD objectForKey:[NSString stringWithFormat:@"%@TestInfoViewController",user.objectId]];
            if (str && [str isEqualToString:@"YES"]) {
                assistant.backgroundColor =RGBA(75, 217, 112, 1);
                assistant.textColor = [UIColor whiteColor];
                assistant.text = @"已通过";
                self.isTest = YES;
            }else{
                assistant.backgroundColor =RGBA(202, 203, 204, 1);
                assistant.textColor = [UIColor whiteColor];
                assistant.text = @"未测试";
                self.isTest = NO;
            }
            
            
        }else if (indexPath.section == 3){
            
            MLUser *user = [MLUser currentUser];
            if (user&&self.isRead) {
                assistant.backgroundColor =RGBA(75, 217, 112, 1);
                assistant.textColor = [UIColor whiteColor];
                assistant.text = @"已读";
                self.isRead = YES;
            }else{
                assistant.backgroundColor =RGBA(202, 203, 204, 1);
                assistant.textColor = [UIColor whiteColor];
                assistant.text = @"未读";
                self.isRead = NO;
            }
            
            
        }
        
        
        assistant.layer.cornerRadius = 7.5;
        assistant.layer.masksToBounds = YES;
        assistant.font = [UIFont fontWithName:FontName size:12];
        assistant.textAlignment = NSTextAlignmentCenter;
        [cell.contentView addSubview:assistant];
        cell.opaque = NO;
        return  cell;
        
    }
    return nil;
}
- (void)byValueAVFile:(AVFile *)avatar andUserAttestationImage:(UIImage *)userAttestationImage
{
    self.loveExperience.avatar = avatar;
    self.selectImage = userAttestationImage;
    self.userAttestationImage = YES;
}
//PhotoAttestationViewControllerDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 1) {
        if (indexPath.row == 0) {
            PhotoAttestationViewController *photoVC = [[PhotoAttestationViewController alloc] init];
            photoVC.delegate = self;
            photoVC.selectImage = self.selectImage;
            [Utils pushTabbarHidden:photoVC Selfvc:self];
        }else{
            MLUserDataViewController *userInfoVC = [[MLUserDataViewController alloc]init];
            userInfoVC.userData = [MLUser currentUser];
            [Utils pushTabbarHidden:userInfoVC Selfvc:self];
        }
    }else if (indexPath.section == 2){
        [self.navigationController pushViewController:[[TestViewController alloc] init] animated:YES];
    }else if (indexPath.section == 3){
        
        WEBViewController *web = [[WEBViewController alloc]init];
        web.WEBURL = @"http://mp.weixin.qq.com/s?__biz=MjM5OTg5MjUyNQ==&mid=210146509&idx=1&sn=40b339d696eea39d4e08c78ae8dec8be#rd";
        [Utils pushTabbarHidden:web Selfvc:self];
        self.isRead = YES;
//        if (![MLUser currentUser].notifyPhoneNum) {
//            BindingMobilePhoneViewController *bindingMPVC = [[BindingMobilePhoneViewController alloc]init];
//            bindingMPVC.delegate = self;
//            [self.navigationController pushViewController:bindingMPVC animated:YES];
//        }else{
//            [self.navigationController pushViewController:[[PhoneViewController alloc]init] animated:YES];
//        }
        
        
    }
}

#pragma mark UITextFieldDelegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    
    self.tableView.frame = CGRectMake(0, -200, DeviceWidth, DeviceHeight);
    return YES;
}
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField;
{
    
    self.tableView.frame = CGRectMake(0, 0, DeviceWidth, DeviceHeight);
    return YES;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}


- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (section == 0) {
        return 10;
    }else if (section == 1){
        return 50;
    }else if (section == 2){
        return 50;
    }else if (section == 3){
        return 50;
    }else{
        return 50;
    }
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    if (section == 0) {
        return nil;
    }else if (section == 1||section == 2||section == 3){
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, DeviceWidth, 50)];
        view.backgroundColor =[UIColor clearColor];
        UILabel *titleLable =[[UILabel alloc] initWithFrame:CGRectMake(20, 5, DeviceWidth-40, 24)];
        
        if (section == 1) {
            titleLable.text = @"资料完整度需要100%,声线是审核的重点哦";
        }else if(section == 2){
            titleLable.text = @"测试你是否适合成为专属恋人";
        }else if (section == 3){
            titleLable.text = @"成为专属恋人后，原先的恋人关系将自动解除";
        }
        titleLable.numberOfLines = 0;
        titleLable.font = [UIFont fontWithName:FontName size:14];
        titleLable.textColor = RGBA(138, 138, 138, 1);
        [view addSubview:titleLable];
        
        return view;
    }else{
        return nil;
    }
    
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return DeviceWidth/320*144;
    }else if (indexPath.section == 1){
        return 50;
    }else if (indexPath.section == 2){
        return 50;
    }else if (indexPath.section == 3){
        return 50;
    }else{
        return 50;
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
